import {
	ref,
	computed
} from 'vue'
import {
	submitOrder,
} from '@/common/api.js'
import {
	getEnv,
	goTo,
	isEmpty
} from '@/common/system.js'
import {
	useCommonStore
} from '@/stores/common.js'
import {
	requestPayment
} from '@/common/platformApi.js'
const commonStore = useCommonStore()
export const provider = ref('alipay') // 支付方式,即提供商
export const loading = ref(false) // 是否提交中
const openid = computed(() => commonStore.openid)
const deviceInfo = computed(() => commonStore.deviceInfo) //获取码牌信息

// 获取订单信息 (微信小程序支付需要openid)
export function getOrderInfo(data) {
	// 不要少了async
	return new Promise(async (resolve, reject) => {
		let param = {
			...deviceInfo.value,
			...data
		}
		console.log('下单数据==》', param);
		let res = await submitOrder(param);
		console.log('下单返回数据===>', res);
		const payBody = res.data.payBody
		if (!payBody && res.data.msg) {
			reject(res)
			uni.showModal({
				content: res.data.msg,
				showCancel: false,
				success: async (res) => {
					if (getEnv() == 'h5-alipay') {
						AlipayJSBridge.call('closeWebview');
					} else {
						goTo('/pages/after-pay/index', {
							type: 'err'
						})
					}
				}
			})
			return
		}
		resolve(payBody)
	})
}
// 支付宝操作
export async function payHandler(orderData) {
	// 支付中
	loading.value = true
	// 1. 发送请求到服务端，服务端生成订单信息，响应预支付订单号
	let orderInfo = await getOrderInfo(orderData);
	if (!orderInfo) {
		uni.showModal({
			content: '获取支付信息失败',
			showCancel: false
		})
		return
	}
	// 2. 请求支付
	requestPayment({
		orderInfo: orderInfo,
	}).then(e => {
		console.log("success", e);
		if (e.resultCode == '9000') {
			uni.showToast({
				title: "支付成功!"
			})
			goTo('/pages/after-pay/index')
		}
		if (e.resultCode == '6001') {
			uni.showToast({
				title: "支付未完成!"
			})
			success: async (res) => {
				goTo('/pages/after-pay/index', {
					type: 'err'
				})
			}
		}

	})
	loading.value = false
	// uni.requestPayment({
	// 	provider: provider.value, // 支付渠道
	// 	orderInfo: orderInfo,
	// 	success: (e) => {
	// 		console.log("success", e);
	// 		uni.showToast({
	// 			title: "支付成功!"
	// 		})
	// 		// 回到订单页面
	// 		// this.navTo('/pages/order/order')
	// 	},
	// 	fail: (e) => {
	// 		console.log("fail", e);
	// 		uni.showModal({
	// 			content: "支付失败，请重试。",
	// 			showCancel: false
	// 		})
	// 	},
	// 	complete: () => {
	// 		loading.value = false;
	// 	}
	// })
}

// 支付宝当面付拉起支付 
const h5AliPayCode = {
	'9000': '订单支付成功',
	'8000': '正在处理中',
	'4000': '订单支付失败',
	'6001': '用户中途取消',
	'6002': '网络连接出错',
	'99': '用户点击忘记密码快捷界面退出(only iOs since 9.5)'
}

function ready(callback) {
	if (window.AlipayJSBridge) {
		callback && callback();
	} else {
		document.addEventListener('AlipayJSBridgeReady', callback, false);
	}
}

function tradePay(tradeNO) {
	ready(function() {
		// 通过传入交易号唤起快捷调用方式(注意tradeNO大小写严格)
		AlipayJSBridge.call("tradePay", {
			tradeNO: tradeNO
		}, function(data) {
			console.log(JSON.stringify(data));
			uni.showModal({
				content: h5AliPayCode[data.resultCode],
				showCancel: false,
				success: async (res) => {
					// if ("9000" == data.resultCode) {
					// 	goTo('/pages/after-pay/index')
					// } else {
					// 	goTo('/pages/after-pay/index', {
					// 		type: 'err'
					// 	})
					// }
					AlipayJSBridge.call('closeWebview');
				}
			})
		});
	});
}
export async function alPayH5(orderData) {
	// 支付中
	loading.value = true
	// 1. 发送请求到服务端，服务端生成订单信息，响应预支付订单号
	let orderInfo = await getOrderInfo(orderData);
	if (!orderInfo) {
		uni.showModal({
			content: '获取支付信息失败',
			showCancel: false,
			// success: async (res) => {
			// 	goTo('/pages/after-pay/index', {
			// 		type: 'err'
			// 	})
			// }
		})
		return
	}
	// 2. 拉起支付
	tradePay(orderInfo);
	loading.value = false

}

// 微信公众号支付
export async function wxPayH5(orderData) {
	loading.value = true
	// 2. 通过 openid 再获取订单信息，
	let orderInfo = await getOrderInfo(orderData)
	// 拉起微信公众号支付
	function onBridgeReady() {
		WeixinJSBridge.invoke('getBrandWCPayRequest', {
				...orderInfo,
				"timeStamp": orderInfo.timestamp, //时间戳，自1970年以来的秒数
				"package": orderInfo.packageVal,
			},
			function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					// 使用以上方式判断前端返回,微信团队郑重提示：
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
				}
			});
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
	loading.value = false;
}
// 微信小程序支付
const wxMpErr = {
	'requestPayment:fail cancel': '用户取消支付，请重新支付',
	'requestPayment:fail jsapi has no permission': '该小程序使用支付功能的权限已被公众平台限制',
}
export async function wxPayHandler(orderData) {
	loading.value = true
	// 2. 通过 openid 再获取订单信息，
	let orderInfo = await getOrderInfo(orderData)
	orderInfo = JSON.parse(orderInfo)
	console.log('orderInfo==>', orderInfo);
	// 3. 通过订单预支付信息，去调用支付接口
	uni.requestPayment({
		...orderInfo,
		timeStamp: orderInfo.timestamp,
		package: orderInfo.packageVal || orderInfo.package,
		success: (res) => {
			console.log('支付成功==>', res);
			uni.showToast({
				title: "支付成功!"
			})
			goTo('/pages/after-pay/index')
		},
		fail: (res) => {
			console.log('原因为:', res);
			uni.showModal({
				content: wxMpErr[res.errMsg] || '支付失败，请重新支付',
				showCancel: false,
				success: async (res) => {
					goTo('/pages/after-pay/index', {
						type: 'err'
					})
				}
			})
		},
		complete: () => {
			loading.value = false;
		}
	})
}